package com.patui.Weibo;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import com.patui.Ui.HomeItemInfo;
import com.patui.Utils.PLog;
import com.patui.Utils.TextUtils;
public class Weibo {
	
	public static String SERVER = "http://api.t.sina.com.cn/";
	public static String URL_OAUTH_TOKEN = "http://api.t.sina.com.cn/oauth/request_token";
	public static String URL_AUTHORIZE = "http://api.t.sina.com.cn/oauth/authorize";
	public static String URL_ACCESS_TOKEN = "http://api.t.sina.com.cn/oauth/access_token";
	public static String callBackUrl = "http://mopa.com";
	public static String APP_KEY = "2749264093";
	public static String APP_SECRET = "b44c586d4fb684f5b3c06eaeeb8a4134";
	private static Weibo mWeiboInstance = null;
	private AccessToken  mAccessToken = null;
	private RequestToken mRequestToken = null;

	private Weibo(){
		Utility.setRequestHeader("Accept-Encoding","gzip");	
		Utility.setTokenObject(this.mRequestToken);
	}
	
	public static Weibo getInstance(){	
		if(mWeiboInstance == null){
			mWeiboInstance = new Weibo();
		}
		return mWeiboInstance;
	}
	
	//设置accessToken
	public void setAccessToken(AccessToken token){
		mAccessToken = token;
	}
	
	public AccessToken getAccessToken(){
		return this.mAccessToken;
	}
	
	public void setupConsumerConfig(String consumer_key, String consumer_secret){
		Weibo.APP_KEY = consumer_key;
		Weibo.APP_SECRET = consumer_secret;
	}
	
	public void setRequestToken(RequestToken token){
		this.mRequestToken = token;
	}
	
	public RequestToken getRequestToken(){
		return this.mRequestToken;
	}
	
	//设置oauth_verifier
	public void SetOauthverifier(String verifier){
		mRequestToken.setVerifier(verifier);
	}
	
	public String request(Context context, String url, WeiboParameters params, String httpMethod, AccessToken token) 
		throws WeiboException{
			Utility.setAuthorization(new RequestHeader());
			String reponse = Utility.openUrl(context, url, httpMethod, params, this.mAccessToken);
			return reponse;
	}
	
	public RequestToken getRequestToken(Context context, String key, String secret, String callback_url) 
		throws WeiboException
	{
		//HttpHeaderFactory是RequestTokenHeader的基类
		Utility.setAuthorization(new RequestTokenHeader());
		WeiboParameters postParams = new WeiboParameters();
		postParams.add("oauth_callback", callback_url);
		String response;
		response = Utility.openUrl(context, Weibo.URL_OAUTH_TOKEN, "POST", postParams, null);
		RequestToken request = new RequestToken(response);
		this.mRequestToken = request;
		return request;
	}
	
	
	public AccessToken generateAccessToken(Context context, RequestToken requestToken) 
		throws WeiboException
	{
		Utility.setAuthorization(new AccessTokenHeader());
		WeiboParameters authParam = new WeiboParameters();
		authParam.add("oauth_verifier", this.mRequestToken.getVerifier()/*"605835"*/);
		authParam.add("source", APP_KEY);
		String response = Utility.openUrl(context, Weibo.URL_ACCESS_TOKEN, "POST", authParam, this.mRequestToken);
		AccessToken accessToken = new AccessToken(response);
		this.mAccessToken = accessToken;
		return accessToken;
	}
	
	
	public AccessToken getXauthAccessToken(Context context, String app_key, String app_secret, String usrname, String password)
		throws WeiboException{
		Utility.setAuthorization(new XAuthHeader());
		WeiboParameters postParams = new WeiboParameters();
		postParams.add("x_auth_username", usrname);
		postParams.add("x_auth_password", password);
		postParams.add("oauth_consumer_key", APP_KEY);
		String rlt = Utility.openUrl(context, Weibo.URL_ACCESS_TOKEN, "POST", postParams, null);
		AccessToken accessToken = new AccessToken(rlt);
		this.mAccessToken = accessToken;
		return accessToken;
	}


	public void authorizeCallBack(int requestCode, int resultCode , Intent data){
		
		
	}
	
	public List<HomeItemInfo> getFriendTimeline(Context mContext)
	{
		List<HomeItemInfo> friendsArray=new ArrayList<HomeItemInfo>();
		try {
			String url = Weibo.SERVER + "statuses/friends_timeline.json";
			WeiboParameters bundle = new WeiboParameters();
			bundle.add("source", Weibo.APP_KEY);
			bundle.add("count","50");
			String response = request(mContext, url, bundle, "GET", getAccessToken());
			JSONArray weiboArray=new JSONArray(response);
			for(int mi=0;mi<weiboArray.length();mi++)
			{
				JSONObject oneWeibo=weiboArray.getJSONObject(mi);
//				PLog.e("debug", oneWeibo.toString());
				if(oneWeibo!=null)
				{
					HomeItemInfo curWeiboInfo=new HomeItemInfo();
					JSONObject user=oneWeibo.getJSONObject("user");
					if(oneWeibo.has("retweeted_status"))
					{
						JSONObject retweeted=oneWeibo.getJSONObject("retweeted_status");
						String retweeedText=retweeted.getString("text");
						JSONObject retUser=retweeted.getJSONObject("user");
						String retUserName=retUser.getString("screen_name");
						retweeedText="@"+retUserName+":"+retweeedText;
						PLog.e("debug", retweeedText);
						curWeiboInfo.setRetweetedText(retweeedText);
					}
					String user_id=user.getString("id");
					String user_name=user.getString("name");
					String user_icon=user.getString("profile_image_url");
					String user_verified=user.getString("verified");
					String article_id=oneWeibo.getString("id");
					String article_create_time=oneWeibo.getString("created_at");
					String article_via=oneWeibo.getString("source");
					boolean article_hava_image=false;
					if(oneWeibo.has("thumbnail_pic")){
						 article_hava_image=true;
	                 }
					String article_text=oneWeibo.getString("text");
					curWeiboInfo.setUserId(user_id);
					curWeiboInfo.setUserName(user_name);
					curWeiboInfo.setUserIcon(user_icon);
					boolean havaV=false;
					if(user_verified.equalsIgnoreCase("true"))
						havaV=true;
					curWeiboInfo.setUserHaveVerified(havaV);
					curWeiboInfo.setArticleId(article_id);
					curWeiboInfo.setArticleHavaImage(article_hava_image);
					curWeiboInfo.setArticleCreatTime(article_create_time);
					curWeiboInfo.setArticleText(article_text);
					curWeiboInfo.setArticleCreatFrom(TextUtils.formatSource(article_via));
					curWeiboInfo.setFileId(user_id);
					friendsArray.add(curWeiboInfo);
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return friendsArray;
	}
	/**
	 * 获取@对象
	 * @param mContext
	 * @return
	 */
	public ArrayList<String> getFollow(Context mContext)
	{
		ArrayList<String> friendsArray=new ArrayList<String>();
		try {
			String url = Weibo.SERVER + "statuses/friends/"+mAccessToken.getmUserId()+".json";
			WeiboParameters bundle = new WeiboParameters();
			bundle.add("source", Weibo.APP_KEY);
			bundle.add("count", String.valueOf(100));
			bundle.add("cursor",String.valueOf(0));
			String response = request(mContext, url, bundle, "GET", getAccessToken());
			if(response!=null&&response.trim().length()>0)
			{
					JSONObject curResult=new JSONObject(response);
					JSONArray userList=curResult.getJSONArray("users");
					for(int mi=0;mi<userList.length();mi++)
					{
						//获取user的JSONObject;
						JSONObject curUser=userList.getJSONObject(mi);
						if(curUser!=null)
						{
							String atName=curUser.getString("name");
							friendsArray.add(atName);
						}
					}
					
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return friendsArray;
	}

	//发文字图片微博
	public String postImage(Context mContext, String file, String content, String lat,String lon) 
	throws WeiboException{
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", Weibo.APP_KEY);
		bundle.add("pic", file);
		bundle.add("status", content);
		if(!TextUtils.isEmpty(lon)){
			bundle.add("long", lon);
		}
		if(!TextUtils.isEmpty(lat)){
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/upload.json";
		try {
			rlt = request(mContext, url, bundle, Utility.HTTPMETHOD_POST, getAccessToken());
		} catch (WeiboException e) {
			throw new WeiboException(e);
		} 
		return rlt;
    }
	//发文字微博
	public String postText(Context mContext, String content, String lat,String lon) 
	throws WeiboException{
		PLog.e("debug", "lat:"+lat+",lon:"+lon);
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", Weibo.APP_KEY);
		bundle.add("status", content);
		if(!TextUtils.isEmpty(lon)){
			bundle.add("long", lon);
		}
		if(!TextUtils.isEmpty(lat)){
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/update.json";
		rlt = request(mContext, url, bundle, Utility.HTTPMETHOD_POST,  getAccessToken());
		return rlt;
	}
	
	//评论微博
	public String postComment(Context mContext,String articleId, String content, String lon, String lat) 
	throws WeiboException{
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", Weibo.APP_KEY);
		bundle.add("comment", content);
		bundle.add("id", articleId);
		bundle.add("comment_ori", "1");
		if(!TextUtils.isEmpty(lon)){
			bundle.add("lon", lon);
		}
		if(!TextUtils.isEmpty(lat)){
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/comment.json";
		rlt = request(mContext, url, bundle, Utility.HTTPMETHOD_POST,  getAccessToken());
		return rlt;
	}
	
	//转发微博
	public String postRetweet(Context mContext,String articleId, String content, String lon, String lat) 
	throws WeiboException{
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", Weibo.APP_KEY);
		bundle.add("status", content);
		bundle.add("id", articleId);
		bundle.add("is_comment", "3");
		if(!TextUtils.isEmpty(lon)){
			bundle.add("lon", lon);
		}
		if(!TextUtils.isEmpty(lat)){
			bundle.add("lat", lat);
		}
		String rlt = "";
		String url = Weibo.SERVER + "statuses/repost.json";
		rlt = request(mContext, url, bundle, Utility.HTTPMETHOD_POST,  getAccessToken());
		return rlt;
	}
	
}
